<template>
    <view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <!-- <view class="cellBox flex_wrap row_between">
            <u--text text="视频类型" color="#000" size="28rpx" />
            <view class="flex_wrap" @click="chooseType()">
                <view class="title">{{ typeName }}</view>
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-picker
            :show="typeShow"
            ref="uPicker"
            :columns="columns"
            keyName="typeName"
            @confirm="confirm"
            @cancel="typeShow = false"
        ></u-picker> -->

        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox flex_wrap row_between">
            <u--text text="课程名称" color="#000" size="28rpx" />
            <view class="flex_wrap" @click="addName()">
                <view class="title">{{ videoName }}</view>
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-line color="#f3f3f3" length="2rpx"></u-line>
        <view class="cellBox flex_wrap row_between">
            <u--text text="排序号" color="#000" size="28rpx" />
            <view class="flex_wrap">
                <u--input
                    placeholder="请输入排序号"
                    border="none"
                    v-model="videoDiversity"
                    type="number"
                    inputAlign="right"
                ></u--input>
            </view>
        </view>
        <!-- <u-line color="#f3f3f3" length="2rpx"></u-line>
        <view style="background: #fff; padding: 30rpx">
            <view class="content huaTiBox">
                <u-textarea
                    ref="isInputFocus"
                    v-model="huaTi"
                    :maxlength="1000"
                    placeholder="请输入您要关联的话题~"
                    autoHeight
                    :customStyle="{
                        backgroundColor: '#F8F8F8',
                        fontSize: '28rpx',
                        border: 'none',
                        minHeight: '120rpx',
                    }"
                ></u-textarea>
                <view class="talkBox" @click="addTalkBtn"># 话题</view>
            </view></view
        > -->
        <view class="cellBox">
            <u--text
                text="上传视频"
                color="#000"
                size="28rpx"
                margin="0 0 24rpx 0"
            />
            <view>
                <u-upload
                    :maxCount="1"
                    :fileList="fileList1"
                    @delete="deleteVideo"
                    @afterRead="afterRead1"
                    @beforeRead="beforeRead1"
                    accept="video"
                    width="196rpx"
                    height="196rpx"
                    compressed
                    maxDuration="30"
                ></u-upload>
            </view>
        </view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox">
            <u--text
                text="章节封面"
                color="#000"
                size="28rpx"
                margin="0 0 24rpx 0"
            />
            <view>
                <u-upload
                    :maxCount="1"
                    :previewFullImage="true"
                    :fileList="fileList"
                    @delete="deletePic"
                    @afterRead="afterRead"
                    width="196rpx"
                    height="196rpx"
                >
                </u-upload>
            </view>
        </view>

        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>

        <view class="bottom">
            <u-button
                :loading="btnLoading"
                text="发布"
                color="#1682FF"
                :disabled="uploadLoading"
                shape="circle"
                @click="sumbit()"
            />
        </view>

        <u-modal
            :show="nameShow"
            showCancelButton
            title="课程名称"
            @confirm="nameConfirm"
            @cancel="nameShow = false"
        >
            <view style="width: 560rpx; margin: 0 auto">
                <u-textarea
                    ref="textareaName"
                    height="300rpx"
                    v-model="videoName1"
                    :customStyle="textAreaCustomStyle"
                    placeholder="请输入内容"
                    fixed
                    count
                    maxlength="100"
                ></u-textarea>
            </view>
        </u-modal>

        <u-modal
            :show="infoShow"
            showCancelButton
            title="视频简介"
            @confirm="infoConfirm"
            @cancel="infoShow = false"
        >
            <view style="width: 560rpx; margin: 0 auto">
                <u-textarea
                    ref="textarea"
                    height="300rpx"
                    v-model="videoInfo1"
                    :customStyle="textAreaCustomStyle"
                    placeholder="请输入内容"
                    fixed
                    count
                    maxlength="100"
                ></u-textarea>
            </view>
        </u-modal>
    </view>
</template>

<script>
import { baseUrl } from "@/config/tendIdConfig";
import { mapGetters } from "vuex";
import { uploadVideo } from "@/api/consultationSalesman.js";
import {
    uploadVideoCustomer,
    getBlogInfoCustomer,
    updateSalesmanVideo,
    getNextVideoNumByVideoSeries,
} from "@/api/customerAgent.js";
export default {
    data() {
        return {
            btnLoading: false,
            uploadLoading: true,
            textAreaCustomStyle: {
                backgroundColor: "#EDEDED",
                color: "#666",
                width: "100%",
                padding: "20rpx",
                paddingBottom: "40rpx",
                boxSizing: "border-box",
                fontSize: "26rpx",
            },
            navbarData: {},
            typeShow: false,
            columns: [],
            videoDiversity: "",
            typeNameId: "",
            nameShow: false,
            videoName: "",
            videoName1: "",
            infoShow: false,
            videoInfo: "",
            videoInfo1: "",
            huaTi: "",
            fileList: [],
            fileList1: [],
            releaseManId: "",
            status: "",
            videoSeries: "",
        };
    },
    mounted() {
        // this.handelData();
    },
    computed: {
        ...mapGetters(["userInfo"]),
    },
    onReady() {
        this.$refs.textarea.setFormatter(this.formatter);
        this.$refs.textareaName.setFormatter(this.formatterName);
    },
    onLoad(o) {
        if (o.releaseManId) this.releaseManId = o.releaseManId;
        if (o.status) {
            this.status = o.status;
            if (this.status === "update") {
                this.handelData(o.id);
                this.uploadLoading = false;
            } else {
                getNextVideoNumByVideoSeries(o.videoSeries).then((res) => {
                    if (res.code == 200) this.videoDiversity = res.data;
                });
            }
        }
        if (o.videoSeries) this.videoSeries = o.videoSeries;
    },
    methods: {
        formatter(value) {
            if (value.length > 100) {
                return value.slice(0, 100);
            } else {
                return value;
            }
        },
        formatterName(value) {
            if (value.length > 100) {
                return value.slice(0, 100);
            } else {
                return value;
            }
        },
        sumbit() {
            if (!this.videoName.length) return uni.$u.toast("请输入课程名称！");
            if (!this.videoDiversity) return uni.$u.toast("请输入排序！");
            if (!this.fileList.length || !this.fileList1.length)
                return uni.$u.toast("请上传图片/视频！");

            this.btnLoading = true;

            const params = {
                checkStatus: 0, //审核状态（0:通过 1:不通过）
                recordType: 9, //业务员课程商品
                releaseStatus: 1, //发布
                releaseManId: this.userInfo.id, //发布人ID
                videoName: this.videoName, //视频名字
                videoSeries: this.videoSeries, //视频系列
                videoDiversity: this.videoDiversity, //视频简介
                videoCover: this.fileList[0]["url"],
                videoUrl: this.fileList1[0]["url"], //视频地址
            };
            // 新增章节
            this.status == "add" &&
                uploadVideoCustomer(params).then((res) => {
                    uni.$u.toast("提交成功");
                    uni.navigateBack({
                        delta: 1,
                    });
                });

            // 编辑章节
            this.status == "update" &&
                updateSalesmanVideo({ id: this.videoData.id, ...params }).then(
                    (res) => {
                        uni.$u.toast("提交成功");
                        uni.navigateBack({
                            delta: 1,
                        });
                    }
                );
        },

        addName() {
            this.videoName1 = this.videoName;
            this.nameShow = true;
        },
        nameConfirm() {
            this.nameShow = false;
            this.videoName = this.videoName1;
        },
        addInfo() {
            this.videoInfo1 = this.videoInfo;
            this.infoShow = true;
        },
        infoConfirm() {
            this.videoInfo = this.videoInfo1;
            this.infoShow = false;
        },
        //初始化开始数据
        async handelData(id) {
            const res = await getBlogInfoCustomer(id);
            if (res.code == 200) {
                this.videoData = res.data;
                this.videoDiversity = this.videoData.videoDiversity;
                this.videoName = this.videoData.videoName;
                this.fileList = [{ url: this.videoData.videoCover }];
                this.fileList1 = [{ url: this.videoData.videoUrl }];
            }
        },
        chooseType() {
            this.typeShow = true;
        },
        // 确认选中的数据
        confirm(e) {
            this.typeName = e.value[0].typeName;
            this.typeNameId = e.value[0].id;
            console.log(this.typeNameId, "mmmm", this.typeName);
            this.typeShow = false;
        },
        async afterRead(event) {
            this.uploadLoading = true;
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList.length;
            lists.map((item) => {
                this.fileList.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                this.uploadLoading = false;
                let item = this.fileList[fileListLen];
                this.fileList.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        deletePic(event) {
            this.fileList.splice(event.index, 1);
        },

        beforeRead1(e) {
            console.log("上3333", e);
        },
        async afterRead1(event, name) {
            this.uploadLoading = true;
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList1.length;
            lists.map((item) => {
                this.fileList1.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result0 = await this.uploadFilePromise0(lists[i].url);
                const result = await this.uploadFilePromise1(
                    result0.uploadParam,
                    event.file
                );
                if (result == 200) {
                    this.uploadLoading = false;
                    let item = this.fileList1[fileListLen];
                    this.fileList1.splice(
                        fileListLen,
                        1,
                        Object.assign(item, {
                            status: "success",
                            message: "",
                            uploadResult: result0.downloadUrl,
                            url: result0.downloadUrl,
                        })
                    );
                    fileListLen++;
                    this.fileList = [
                        {
                            status: "success",
                            message: "",
                            uploadResult:
                                result0.downloadUrl +
                                "?x-oss-process=video/snapshot,t_1000,f_jpg",
                            url:
                                result0.downloadUrl +
                                "?x-oss-process=video/snapshot,t_1000,f_jpg",
                        },
                    ];
                }
            }

            console.log(event, name, "object :>> ", this.fileList);
        },
        deleteVideo(event) {
            this.fileList1.splice(event.index, 1);
        },
        async uploadFilePromise0(url) {
            const that = this;

            return new Promise((resolve, reject) => {
                const token =
                    this.$store.getters?.customer_token ||
                    uni.getStorageSync("customer_token");
                uni.request({
                    url: baseUrl + "/customer/oss_to_direct/getUploadUrl",
                    method: "POST",
                    header: {
                        Authorization: token,
                    },
                    data: {
                        fileName: url,
                        scene: 2,
                    },
                    success: (res) => {
                        console.log("res :>> ", res.data);
                        const result = res.data;
                        if (result.code === 200) {
                            /*  uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            }); */
                            setTimeout(() => {
                                resolve(result.data);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },
        async uploadFilePromise1(result0, file) {
            const formData = {
                OSSAccessKeyId: result0.accessid,
                policy: result0.policy,
                Signature: result0.signature,
                key: result0.key,
                dir: result0.dir,
                host: result0.host,
                expire: result0.expire * 1,
                "x-oss-object-acl": "public-read",
                success_action_status: "200",
                // file: file.url,
            };
            const that = this;

            return new Promise((resolve, reject) => {
                const token = uni.getStorageSync("access_token");
                let a = uni.uploadFile({
                    url: "https://" + result0.host,
                    filePath: file.url,
                    formData,
                    name: "file", //必须填file
                    success: (res) => {
                        console.log(res, 333);
                        const result = res.data;
                        if (res.statusCode === 200) {
                            uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                resolve(200);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },
        async uploadFilePromise(url) {
            const that = this;

            return new Promise((resolve, reject) => {
                const token = uni.getStorageSync("access_token");
                let a = uni.uploadFile({
                    url: `${baseUrl}/${this.$store.getters?.authority}/fileOss/uploadFileImg`,
                    filePath: url,
                    header: {
                        "Content-Type": "multipart/form-data",
                        Authorization: `Bearer ${token}` || "",
                    },
                    name: "file",
                    success: (res) => {
                        const result = JSON.parse(res.data);
                        if (result.code === 200) {
                            uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                resolve(result.data);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },
    },
};
</script>
<style lang="scss" scoped>
page {
    background: #f5f5f5;
    color: #333333;
}

.cellBox {
    background-color: #ffffff;
    padding: 34rpx 28rpx;
    /* line-height: 112rpx; */
    font-size: 32rpx;
    color: #3d3d3d;
}

.title {
    overflow: hidden;
    width: 500rpx;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: end;
}
.bottom {
    width: 100%;
    padding: 10rpx 40rpx 60rpx;
    box-sizing: border-box;
}
.huaTiBox {
    ::v-deep .u-textarea__field {
        color: #588bf3 !important;
    }
}
.content {
    background: #f8f8f8;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    padding-bottom: 20rpx;
}
.talkBox {
    width: 112rpx;
    height: 40rpx;
    background: #588bf3;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    line-height: 40rpx;
    text-align: center;
    color: #fff;
    font-weight: 400;
    font-size: 28rpx;
    margin: 0 0 16rpx 60rpx;
}
::v-deep .u-upload__deletable {
    scale: 2;
}
::v-deep .u-upload__deletable__icon {
    top: 2px !important;
    right: 2px !important;
    scale: 1 !important;
}
</style>
